<template>
  <div class="high-performance">
    <div :id="chartId" ref="chartRef" class="encapsulation-charts"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref, watchEffect } from 'vue';
import { propsConfig } from '@/interface/index';
import {
  SciChartSurface,
  NumericAxis,
  FastLineRenderableSeries,
  SplineLineRenderableSeries,
  FastColumnRenderableSeries,
  EDataPointWidthMode,
  XyDataSeries,
  SciChartJsNavyTheme,
  EAxisAlignment,
  ELabelAlignment,
  ENumericFormat,
  NumberRange,
  RolloverModifier,
  XySeriesInfo,
  MouseWheelZoomModifier,
  ZoomPanModifier,
  // RubberBandXyZoomModifier,
  ZoomExtentsModifier,
  HorizontalLineAnnotation,
  ELabelPlacement,
  XAxisDragModifier,
  YAxisDragModifier
} from 'scichart';
import { color } from 'echarts';

const chartId = ref('encapsulation-chart-' + Math.random().toString(36).substring(2, 9));

const chartRef = ref<HTMLDivElement | null>(null);

const chartInitializationPromise = ref<Promise<any> | undefined>(undefined);

// 父组件传递数据(将部分常用功能封装成echarts方式，变得更加简单易用)
const props = withDefaults(defineProps<propsConfig>(), {
  options: {
    tooltip: {
      trigger: 'axis', // 触发类型：坐标轴触发
      axisPointer: {
        type: 'line', // 指示器类型：直线
        lineStyle: {
          color: '#50C7E077', // 竖线颜色
          width: 2, // 线宽
          type: 'dashed', // 实线
        },
      },
    },
    title: {
      text: 'Y轴',
      textAlign: ELabelAlignment.Left,
      textStyle: {
        fontSize: 22,
        color: '#50C7E077',
      },
    },
    grid: {
      left: 10,
      right: 50,
      top: 15,
      bottom: 10,
    },
    xAxis: {
      name: 'x轴',
      show: true,
      axisLabel: {
        color: '#50C7E077',
        fontSize: 16,
      },
      color: '#50C7E077',
      data: [1, 2, 3, 4, 5, 6, 7],
    },
    yAxis: {
      name: '',
      min: 0,
      max: 1500,
      show: true,
      axisLabel: {
        color: '#50C7E077',
        fontSize: 16,
      },
    },
    series: [
      {
        name: 'Email',
        type: 'line',
        itemStyle: {
          color: 'red',
        },
        lineStyle: {
          width: 3,
          // color: 'red',
          type: 'dashed', // 简单虚线（等间距）
          dashArray: [10, 10], // 5px 实线 + 5px 空白
        },
        isDigitalLine: false, // 阶梯状折线图(二选一)
        smooth: true, // 平滑折线图(二选一)
        data: [120, 132, 101, 134, 90, 230, 210],
        markLine: {
          data: [
            {
              yAxis: 900, // 在 y=150 处画一条水平线
              name: '阈值线',
              lineStyle: {
                color: 'yellow',
                type: 'dashed',
              },
              // 设置标签样式
              label: {
                color: '#333', // 文字颜色（深灰色）
                fontSize: 12, // 字体大小
              },
            },
          ],
        },
      },
      {
        name: 'Union Ads',
        type: 'bar',
        itemStyle: {
          color: '#50C7E077',
        },
        lineStyle: {
          width: 3,
          color: '#1890FF',
        },
        data: [220, 182, 191, 234, 290, 330, 310],
      },
      {
        name: 'Video Ads',
        type: 'line',
        itemStyle: {
          color: '#50C7E077',
        },
        lineStyle: {
          width: 3,
          color: '#1890FF',
        },
        data: [150, 232, 201, 154, 190, 330, 410],
      },
      {
        name: 'Direct',
        type: 'line',
        itemStyle: {
          color: '#50C7E077',
        },
        lineStyle: {
          width: 3,
          color: '#1890FF',
        },
        data: [320, 332, 301, 334, 390, 330, 320],
      },
      {
        name: 'Search Engine',
        type: 'line',
        itemStyle: {
          color: '#50C7E077',
        },
        lineStyle: {
          width: 3,
          color: '#1890FF',
        },
        data: [820, 932, 901, 934, 1290, 1330, 1320],
      },
    ],
  },
  text: '暂无数据', // 可选属性
  empty: false,
});

// 初始化
const initChart = async () => {
  // 创建 SciChartSurface
  const { sciChartSurface, wasmContext } = await SciChartSurface.create(chartId.value, {
    theme: new SciChartJsNavyTheme(),
    title: props.options.title.text,
    titleStyle: {
      fontSize: props.options.title.textStyle.fontSize,
      alignment: props.options.title.textAlign,
      color: props.options.title.textStyle.color,
      padding: { top: 30, left: 20, right: 0, bottom: 0 },
    },
  });

  sciChartSurface.padding = props.options.grid;

  // 创建 X 轴和 Y 轴
  sciChartSurface.xAxes.add(
    new NumericAxis(wasmContext, {
      isVisible: props.options.xAxis.show,
      axisTitle: props.options.xAxis.name,
      axisTitleStyle: {
        alignment: ELabelAlignment.Right,
        //  rotation: 90, // 0 度（竖向显示）
        background: 'red', // 颜色
        fontSize: 18, // 字体大小
        fontWeight: 'bold', // 字体粗细
        // padding: { top: 30 }, // 向下移动标题（模拟“上方”效果）
      },
      labelStyle: {
        color: props.options.xAxis.axisLabel.color,
        fontSize: props.options.xAxis.axisLabel.fontSize,
      },
      // visibleRange: new NumberRange(0.1, 80),
      keepLabelsWithinAxis: false,
      axisBorder: { color: '#50C7E077', borderTop: 1 },
    })
  );
  sciChartSurface.yAxes.add(
    new NumericAxis(wasmContext, {
      isVisible: props.options.yAxis.show,
      axisTitle: props.options.yAxis.name,
      axisAlignment: EAxisAlignment.Left,
      axisTitleStyle: {
        alignment: ELabelAlignment.Right,
        rotation: 0, // 0 度（横向显示）
        labelFormat: ENumericFormat.Decimal,
        color: '#FF0000', // 颜色
        fontSize: 18, // 字体大小
        fontWeight: 'bold', // 字体粗细
        offset: { x: 200, y: -200 }, // 向右移动 0px，向上移动 20px
        // padding: { top: 0, left: 0, right: 0, bottom: 10 }, // 微调位置（左移5px对齐轴线）
      },
      labelStyle: {
        color: props.options.yAxis.axisLabel.color,
        fontSize: props.options.yAxis.axisLabel.fontSize,
      },
      visibleRange:
        props.options.yAxis?.min !== undefined && props.options.yAxis?.max !== undefined
          ? new NumberRange(props.options.yAxis.min, props.options.yAxis.max)
          : null,
      keepLabelsWithinAxis: false,
      axisBorder: { color: '#50C7E077', borderRight: 1 },
    })
  );

  // 鼠标悬停时显示 x 轴的指示线
  const tooltipModifier = new RolloverModifier({
    showTooltip: true, // 显示工具提示
    showAxisLabel: true, // 显示轴标签
    showRolloverLine: true, // 显示滚动线
    rolloverLineStroke: props.options?.tooltip?.axisPointer?.lineStyle?.color || '#FF6600',
    rolloverLineStrokeThickness: props.options?.tooltip?.axisPointer?.lineStyle?.width || 2, // 滚动线宽度
    rolloverLineStrokeDashArray:
      props.options?.tooltip?.axisPointer?.lineStyle?.type === 'dashed' ? [2, 2] : null, // 虚线
  });

  if (props.options.series && props.options.series.length > 0) {
    sciChartSurface.chartModifiers.add(tooltipModifier);
    for (let seriesCount = 0; seriesCount < props.options.series.length; seriesCount++) {
      const xValues = [];
      const yValues = [];

      xValues.push(...[1, 2, 3, 4, 5, 6, 7]);
      yValues.push(...props.options.series[seriesCount]?.data);
      const xyDataSeries = new XyDataSeries(wasmContext, {
        xValues,
        yValues,
      });

      let commonSeries;
      switch (props.options.series[seriesCount].type) {
        case 'line':
          if (props.options.series[seriesCount]?.smooth) {
            commonSeries = new SplineLineRenderableSeries(wasmContext, {
              stroke:
                props.options.series[seriesCount]?.lineStyle?.color ||
                props.options.series[seriesCount]?.itemStyle?.color ||
                '#FF6600',
              strokeThickness: props.options.series[seriesCount]?.lineStyle?.width || 5,
              dataSeries: xyDataSeries,
              isDigitalLine: props.options.series[seriesCount]?.isDigitalLine || false, // markLine阶梯形状
              strokeDashArray:
                props.options.series[seriesCount]?.lineStyle?.type === 'dashed'
                  ? props.options.series[seriesCount]?.lineStyle?.dashArray || [2, 2]
                  : [], // 虚线样式
            });
          } else {
            commonSeries = new FastLineRenderableSeries(wasmContext, {
              stroke:
                props.options.series[seriesCount]?.lineStyle?.color ||
                props.options.series[seriesCount]?.itemStyle?.color ||
                '#FF6600',
              strokeThickness: props.options.series[seriesCount]?.lineStyle?.width || 5,
              dataSeries: xyDataSeries,
              isDigitalLine: props.options.series[seriesCount]?.isDigitalLine || false, // markLine阶梯形状
              strokeDashArray:
                props.options.series[seriesCount]?.lineStyle?.type === 'dashed'
                  ? props.options.series[seriesCount]?.lineStyle?.dashArray || [2, 2]
                  : [], // 虚线样式
            });
          }
          break;
        case 'bar':
          commonSeries = new FastColumnRenderableSeries(wasmContext, {
            fill: 
              props.options.series[seriesCount]?.lineStyle?.color ||
              props.options.series[seriesCount]?.itemStyle?.color ||
              '#FF6600',
            stroke:
              props.options.series[seriesCount]?.lineStyle?.color ||
              props.options.series[seriesCount]?.itemStyle?.color ||
              '#FF6600',
            strokeThickness: 2,
            // yAxisId: 'Absolute',
            dataPointWidthMode: EDataPointWidthMode.Absolute,
            dataPointWidth: 8,
            dataSeries: xyDataSeries, // 数据源
          });
        default:
          break;
      }

      commonSeries.rolloverModifierProps.tooltipDataTemplate = (
        seriesInfo: XySeriesInfo
      ): string[] => {
        const valuesWithLabels: string[] = [];
        const xySeriesInfo = seriesInfo as XySeriesInfo;
        valuesWithLabels.push(xySeriesInfo.formattedXValue);
        valuesWithLabels.push('Y Value: ' + xySeriesInfo.formattedYValue);
        return valuesWithLabels;
      };

      sciChartSurface.renderableSeries.add(commonSeries);

      // 水平标注线
      if (
        props.options.series[seriesCount]?.markLine &&
        Object.keys(props.options.series[seriesCount]?.markLine).length !== 0
      ) {
        props.options.series[seriesCount]?.markLine?.data?.forEach(markLine => {
          if (markLine?.lineStyle?.dashArray || markLine?.lineStyle?.type === 'dashed') {
            sciChartSurface.annotations.add(
              new HorizontalLineAnnotation({
                labelPlacement: ELabelPlacement.TopRight,
                showLabel: true,
                stroke: markLine?.lineStyle?.color || '#3388FF',
                strokeThickness: 2,
                strokeDashArray: markLine?.lineStyle?.dashArray || [5, 5],
                y1: markLine?.yAxis,
                axisLabelFill: markLine?.lineStyle?.color || '#3388FF',
                labelValue: markLine?.lineStyle?.name,
                axisLabelStroke: markLine?.label?.color || 'White',
                axisFontSize: markLine?.label?.fontSize || 20,
              })
            );
          } else {
            // 水平线
            sciChartSurface.annotations.add(
              new HorizontalLineAnnotation({
                labelPlacement: ELabelPlacement.Axis,
                showLabel: true,
                stroke: '#FF6600',
                strokeThickness: 2,
                y1: 900,
                axisLabelFill: '#FF6600',
                axisLabelStroke: '#333',
                axisFontSize: 20,
              })
            );
          }
        });
      }
    }
  }

  const mouseWheelZoomModifier = new MouseWheelZoomModifier();
  const zoomPanModifier = new ZoomPanModifier();
  // const rubberBandZoomModifier = new RubberBandXyZoomModifier();
  const zoomExtentsModifier = new ZoomExtentsModifier(); // 向图表添加缩放、平移行为

  // 鼠标滚轮缩放、平移和双击以缩放以适应
  sciChartSurface.chartModifiers.add(zoomExtentsModifier);
  sciChartSurface.chartModifiers.add(zoomPanModifier);
  // sciChartSurface.chartModifiers.add(rubberBandZoomModifier);
  sciChartSurface.chartModifiers.add(mouseWheelZoomModifier);
  sciChartSurface.chartModifiers.add(
    new XAxisDragModifier(),         // 4. X轴拖动修饰器
    new YAxisDragModifier()          // 5. Y轴拖动修饰器
);

  // sciChartSurface.performanceOverlay.showPerformanceMetrics = true;
};

// 适应父组件大小
const resizeChart = () => {};

// 清除图表数据
const clearChart = () => {};

// 销毁图表
const destroyChart = () => {};

/**
 * vue生命周期做相应的处理
 */

//  挂载
onMounted(() => {
  initChart();
});

// 卸载
onUnmounted(() => {});

// 监听数据变化
watchEffect(() => {});
</script>

<style lang="scss" scoped>
.high-performance {
  width: 100%;
  height: 100%;

  .encapsulation-charts {
    width: 100%;
    height: 100%;
  }
}
</style>
